import 'dart:math';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:flutter_rider/utils/extension.dart';

class Cluster {
  List<dynamic> pts = [];
  LatLng center = const LatLng(0.0, 0.0);
}

class ClusterKit {
  final List<Cluster> _clusters = [];
  double _zoom = 0;

  List<Cluster> getData() {
    return _clusters;
  }

  void calcPoints(List<dynamic> points, double zoom) {
    _zoom = zoom;
    for (var pt in points) {
      if(pt["lat"]!="" && pt["lng"]!=""){
        Cluster? cluster = getCluster(toDouble(pt["lat"]), toDouble(pt["lng"]));
        if (cluster != null) {
          cluster.pts.add(pt);
        } else {
          cluster = Cluster();
          cluster.center = LatLng(toDouble(pt["lat"]), toDouble(pt["lng"]));
          cluster.pts.add(pt);
          _clusters.add(cluster);
        }
      }
    }
  }

  Cluster? getCluster(double lat, double lng) {
    Cluster? foundCluster;
    double lastDistance = double.maxFinite;
    for (var element in _clusters) {
      var distance = AMapTools.distanceBetween(LatLng(lat, lng), LatLng(element.center.latitude, element.center.longitude));
      if (distance < 6 * getScale() && distance < lastDistance) {
        //归纳到距离最近的点
        foundCluster = element;
        lastDistance = distance;
      }
    }
    return foundCluster;
  }

  num getScale() {
    return pow(2, 20 - _zoom);
  }
}